import axios from 'axios'
import router from '../router'

export default {
  export(url, params, origin) {
    let token = window.localStorage.adminLogin ? JSON.parse(window.localStorage.adminLogin).token : ""
    axios.defaults.headers.common['token'] = token
    return new Promise((resolve, reject) => {
      axios.post(url, params, {responseType: 'blob'})
        .then(res => {
          let result = res.data
          let head = res.headers['content-disposition']
          let fname = '';
          if (head) {
            try {
              let info = head.split(';')
              info.forEach(item => {
                if (item.indexOf('filename') >= 0) {
                  fname = item.split('=')[1];
                  let reg = new RegExp('"', "g");
                  fname = fname.replace(reg, "");
                  // 终止循环
                  throw new Error("break")
                }
              })
            } catch (err) {
            }
          }
          if (fname !== '') {
            let blob = new Blob([result])
            let downloadElement = document.createElement('a');
            let href = window.URL.createObjectURL(blob); //创建下载的链接
            downloadElement.href = href;
            downloadElement.download = decodeURIComponent(fname); //下载后文件名
            document.body.appendChild(downloadElement);
            downloadElement.click(); //点击下载
            document.body.removeChild(downloadElement); //下载完成移除元素
            window.URL.revokeObjectURL(href);
            resolve && resolve(result)
          } else {
            let reader = new FileReader();
            reader.readAsText(result);
            reader.onload = e => {
              let rst = JSON.parse(e.target.result)
              if (!origin && rst.code === "11000001") {
                window.localStorage.removeItem('adminLogin')
                router.replace({name: 'login'})
                reject && reject(rst.message)
              } else if (!origin && rst.code === "10000004") {
                router.replace({name: '500'})
                reject && reject(rst.message)
              }
            };
          }
        })
        .catch(err => {
          reject && reject(err.toString())
        })
    })
  },
  post(url, params, origin) {
    let token = window.localStorage.adminLogin ? JSON.parse(window.localStorage.adminLogin).token :""
    axios.defaults.headers.common['token'] = token
    return new Promise((resolve, reject) => {
      axios.post(url, params)
        .then(res => {
          let result = res.data
          if (!origin && result.code === "11000001") {
            window.localStorage.removeItem('adminLogin')
            router.replace({name: 'login'})
            reject && reject(result.message)
          } else if (!origin && result.code === "10000004") {
            router.replace({name: '500'})
            reject && reject(result.message)
          }
          resolve && resolve(result)
        })
        .catch(err => {
          reject && reject(err.toString())
        })
    })
  },

  get(url, params, origin) {
    let token = window.localStorage.adminLogin ? JSON.parse(window.localStorage.adminLogin).token :""
    axios.defaults.headers.common['token'] = token
    return new Promise((resolve, reject) => {
      axios.get(url, {params})
        .then(res => {
          let result = res.data
          if (!origin && result.code === "11000001") {
            window.localStorage.removeItem('adminLogin')
            router.replace({name: 'login'})
            reject && reject(result.message)
          } else if (!origin && result.code === "10000004") {
            router.replace({name: '500'})
            reject && reject(result.message)
          }
          resolve && resolve(result)
        })
        .catch(err => {
          reject && reject(err.toString())
        })
    })
  },

  auto(url, params, origin) {
    return window.environment === 'production' ? this.post(url, params, origin) : this.get(url, params, origin)
  }
}
